<script setup lang="ts">
import CopyOutlined from "@ant-design/icons-vue/CopyOutlined";
import {message} from "ant-design-vue";
import {AxiosPromise} from "axios";
import {WxtBizCode, WxtUtils} from "~/contentScripts/views/wxt/lib/wxtUtils";
import WxtModal from "~/contentScripts/views/wxt/wxt-modal.vue";

const props = defineProps({
  bizCode: {
    type: String as PropType<WxtBizCode>,
    default: WxtBizCode.关键字推广,
  },
  rows: {
    type: Array as PropType<any[]>,
    default: () => [],
  },
  value: {
    type: Array as PropType<any[]>,
    default: () => [],
  },
  plans: {
    type: Array as PropType<any[]>,
    default: () => [],
  },
});
const visible = ref<boolean>(false);
const type = ref<string>('overall');
const selectOptions = [
  {
    title: '综合推荐',
    value: 'overall',
  },
  {
    title: '趋势主题',
    value: 'trendTheme',
  }
];
const columns = [
  {
    title: '词包名称',
    dataIndex: 'wordPackageName',
    width: 160,
    dataType: 'custom',
    slot: 'wordPackageName',
  },
  {
    title: '单元名称',
    dataIndex: 'item.title',
    width: 240,
    dataType: 'custom',
    slot: 'title',
  },
  {
    title: '计划名称',
    dataIndex: 'plan.campaignName',
    width: 160,
    dataType: 'custom',
    slot: 'campaignName',
  },
  {
    title: '卖点主题词',
    dataIndex: 'themeWordList',
    dataType: 'customRender',
    render: (text: string[]) => {
      return text.join(',');
    },
  },
  {
    title: '流量放大系数',
    dataIndex: 'multiFactor',
    width: 140,
  },
  {
    title: '预估展现量',
    dataIndex: 'impression',
    width: 120,
  },
  {
    title: '基础出价',
    dataIndex: 'systemPrice',
    width: 100,
  },
  {
    title: '出价',
    dataIndex: 'bidPrice',
    width: 100,
    dataType: 'custom',
    slot: 'bidPrice',
    render: (text: string, record: any) => {
      return text;
    },
  },
  {
    title: '关键词举例',
    dataIndex: 'simpleWordList',
    dataType: 'customRender',
    render: (text: string[]) => {
      return text.join(',');
    },
  },
  {
    title: '操作',
    width: 80,
    dataType: 'custom',
    slot: 'action',
  },
]
const copy = (text: string) => {
  navigator.clipboard.writeText(text).then(() => {
    message.success('复制成功')
  }).catch(() => {
    message.error('复制失败')
  });
}
const dataSource = ref<any[]>([]);
const loadData = () => {
  dataSource.value = [];
  props.rows.forEach((item: any) => {
    let r: null | AxiosPromise = null;
    if (typeof item.campaignId !== 'undefined' && typeof item.adgroupId !== 'undefined') { // 单元
      r = WxtUtils.customRequest('https://one.alimama.com/wordpackage/suggest/kr/list.json', props.bizCode, {
        campaignId: item.campaignId,
        adgroupId: item.adgroupId,
        type: type.value,
      });
    } else if (typeof item.itemId) { // 计划
      r = WxtUtils.customRequest('https://one.alimama.com/wordpackage/suggest/kr/list.json', props.bizCode, {
        materialId: item.itemId,
        type: type.value,
      });
    }
    if (r !== null) {
      r.then((res: any) => {
        let da = res.data.data.list.map((it: any) => {
          return {
            ...it,
            item,
          }
        });
        if (typeof item.campaignId !== 'undefined' && typeof item.adgroupId !== 'undefined') {
          da = da.map((it: any) => {
            return {
              id: item.campaignId + '-' + item.adgroupId + '-' + it.wordPackageId,
              ...it,
              systemPrice:it.bidPrice,
              item: {
                itemId: item.material.materialId,
                ...item.material,
              },
              plan: {
                campaignName: item.campaignName,
                campaignId: item.campaignId,
                adgroupId: item.adgroupId,
              },
            }
          });

          dataSource.value = dataSource.value.concat(da);
        } else {
          props.plans.forEach((plan: any) => {
            let ddd: any[] = [];
            da.forEach((it: any) => {
              ddd.push({
                id: plan.campaignId + '-' + it.wordPackageId + '-' + it.itemId,
                ...it,
                systemPrice:it.bidPrice,
                plan: {
                  campaignName: plan.campaignName,
                  campaignId: plan.campaignId,
                },
              });
            });
            dataSource.value = dataSource.value.concat(ddd);
          })
          // console.log(ddd);
        }
        console.log(dataSource.value);
      });
    } else {
      message.error('数据错误');
    }
  });
}
const emit = defineEmits([
  "ok",
]);
watch(() => props.rows, (val) => {
  if (val.length) {
    loadData();
  }
}, {
  deep: true
});
watch(() => type.value, (val) => {
  if (props.rows.length) {
    loadData();
  }
});
onMounted(() => {
  if (props.rows.length) {
    loadData();
  }
});
const remove = (row: any) => {
  // 通过ID删除
  const index = dataSource.value.findIndex((item: any) => item.id === row.id);
  if (index !== -1) {
    dataSource.value.splice(index, 1);
  }
}
const selectedRows = ref<any[]>([]);
const ok = () => {
  emit('ok', selectedRows.value.map((item: any) => {
    return {
      ...item,
    }
  }));
  visible.value = false;
}
const bidPrice = ref<number>(1);
const modifyBidPrice = () => {
  if (selectedRows.value.length === 0) {
    message.error('请选择需要修改出价的词包');
    return;
  }
  selectedRows.value.forEach((item: any) => {
    let index = dataSource.value.findIndex((it: any) => it.id === item.id);
    if (index !== -1) {
      dataSource.value[index].bidPrice = bidPrice.value;
    }
  });
  message.success('修改成功');
}
const modifyPrice = (e: number, row: any) => {
  let index = dataSource.value.findIndex((it: any) => it.id === row.id);
  if (index !== -1) {
    dataSource.value[index].bidPrice = e;
  }
}
</script>

<template>
  <div @click="()=>visible=true" style="display: inline-block;">
    <slot>
      <a-button type="primary" size="small">批量添加词包</a-button>
    </slot>
  </div>
  <wxt-modal title="批量添加词包" v-model:visible="visible" width="95%">
    <base-table table-name="批量添加词包" v-model:selected-rows="selectedRows" selection row-key="id" :columns="columns"
                :data-source="dataSource"
    >
      <template #toolbar>
        <a-select v-model:value="type" size="small" style="width: 120px;">
          <a-select-option v-for="item in selectOptions" :value="item.value" :key="item.value">
            {{ item.title }}
          </a-select-option>
        </a-select>
      </template>
      <template #title="row">
        <a-row type="flex" class="adgroupName" :gutter="5">
          <a-col>
            <a-popover placement="right">
              <template #content>
                <img :src="row.item.imgUrl"
                     style="width: 200px;height: 200px;"
                />
              </template>
              <img :src="row.item.imgUrl"
                   style="width: 60px;height: 60px;border-radius: 5px;"
              />
            </a-popover>
          </a-col>
          <a-col flex="1" class="title">
            <a-tooltip :title="row.item.title">
              <span style="
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            line-clamp: 2;
            -webkit-box-orient: vertical;"
              >{{ row.item.title }}</span>
            </a-tooltip>
            <div>
              <a-space>
                <span style="color: #666;">ID: {{ row.item.itemId }}</span>
                <CopyOutlined style="color: #1677ff;cursor: pointer;font-size: 12px;" @click="copy(row.item.itemId)"/>
              </a-space>
            </div>
          </a-col>
        </a-row>
      </template>
      <template #campaignName="row">
        <a-row type="flex" class="adgroupName" :gutter="5">
          <!--            <a-col>-->
          <!--              <a-popover placement="right">-->
          <!--                <template #content>-->
          <!--                  <img :src="row.imgUrl"-->
          <!--                       style="width: 200px;height: 200px;"-->
          <!--                  />-->
          <!--                </template>-->
          <!--                <img :src="row.imgUrl"-->
          <!--                     style="width: 60px;height: 60px;border-radius: 5px;"-->
          <!--                />-->
          <!--              </a-popover>-->
          <!--            </a-col>-->
          <a-col flex="1" class="title">
            <a-tooltip :title="row.title">
              <span style="
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            line-clamp: 2;
            -webkit-box-orient: vertical;"
              >{{ row.plan.campaignName }}</span>
            </a-tooltip>
            <div>
              <a-space>
                <span style="color: #666;">ID: {{ row.plan.campaignId }}</span>
                <CopyOutlined style="color: #1677ff;cursor: pointer;font-size: 12px;"
                              @click="copy(row.plan.campaignId)"
                />
              </a-space>
            </div>
          </a-col>
        </a-row>
      </template>
      <template #bidPrice="row">
        <a-input-number :value="row.bidPrice" @input="(e)=>modifyPrice(e,row)" size="small" style="width: 100%;"/>
      </template>
      <template #action="row">
        <a-button type="link" danger size="small" @click="()=>remove(row)">删除</a-button>
      </template>
    </base-table>
    <a-divider style="margin-top: 10px;"/>
    <a-row type="flex">
      <a-col>
        <a-space>
          出价：<a-input-number v-model:value="bidPrice" size="small" style="width: 100px;"/>
          <a-button type="primary" size="small" @click="modifyBidPrice">应用</a-button>
        </a-space>
      </a-col>
      <a-col flex="1">
      </a-col>
      <a-col>
        <a-space>
          <a-button @click="()=>visible=false">取消</a-button>
          <a-button type="primary" @click="()=>ok()">确定</a-button>
        </a-space>
      </a-col>
    </a-row>
  </wxt-modal>
</template>

<style lang="less" scoped>
.product {
  .title {
    // 一行超出隐藏
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .hover-show {
    display: none;
  }

  &:hover {
    .hover-show {
      display: block;
    }
  }
}
</style>
